//
//  FishRulesViewController.m
//  WHTestDome
//
//  Created by Assistant on 9/22/25.
//

#import "FishRulesViewController.h"

@interface TagLabel : UILabel
@end

@implementation TagLabel
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
        self.textColor = [UIColor colorWithHexString:@"#767676" alpha:1.0];
        self.font = [UIFont systemFontOfSize:14 weight:UIFontWeightLight];
        self.textAlignment = NSTextAlignmentCenter;
        self.layer.cornerRadius = 16.0;
        self.layer.masksToBounds = YES;
        self.layer.borderColor = [UIColor colorWithWhite:0.85 alpha:1.0].CGColor;
        self.layer.borderWidth = 0.5;
        // Use frame-based layout for flow positioning; avoid adding constraints here
        self.translatesAutoresizingMaskIntoConstraints = YES;
    }
    return self;
}
@end

@interface FishRulesViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIStackView *stack;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray<NSDictionary *> *rules;

@end

@implementation FishRulesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.scrollView];

    UIView *content = [[UIView alloc] initWithFrame:self.scrollView.bounds];
    content.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.scrollView addSubview:content];

    CGFloat padding = 16.0;
    CGFloat y = padding;

    // 钓费卡片
    UIView *feeCard = [self buildFeeCardWithWidth:self.view.bounds.size.width - padding * 2];
    feeCard.frame = CGRectMake(padding, y, feeCard.bounds.size.width, feeCard.bounds.size.height);
    [content addSubview:feeCard];
    y = CGRectGetMaxY(feeCard.frame) + 16.0;

    // 规则卡片（表格）
    UIView *ruleCard = [self buildRuleCardWithWidth:self.view.bounds.size.width - padding * 2];
    ruleCard.frame = CGRectMake(padding, y, ruleCard.bounds.size.width, ruleCard.bounds.size.height);
    [content addSubview:ruleCard];
    y = CGRectGetMaxY(ruleCard.frame) + 24.0;

    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, y);
}

- (UIView *)buildFeeCardWithWidth:(CGFloat)width {
    UIView *card = [[UIView alloc] initWithFrame:CGRectZero];
    card.backgroundColor = [UIColor systemBackgroundColor];
    card.layer.cornerRadius = 12.0;
    card.layer.masksToBounds = YES;

    // 标题与左侧色条
    UIView *indicator = [[UIView alloc] initWithFrame:CGRectMake(12, 18, 4, 18)];
    indicator.backgroundColor = whBlueColor;
    indicator.layer.cornerRadius = 2.0;
    [card addSubview:indicator];

    UILabel *title = [[UILabel alloc] initWithFrame:CGRectZero];
    title.text = @"钓费";
    title.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
    title.textColor = [UIColor labelColor];
    title.frame = CGRectMake(CGRectGetMaxX(indicator.frame) + 8, 12, 200, 28);
    [card addSubview:title];

    NSArray<NSString *> *tags = @[ @"鲢鳙票 3小时 158元", @"鲢鳙青鱼票 5小时 238元",
                                   @"鲢鳙青鱼票 8小时 360元", @"普钓票 5小时 158元",
                                   @"普钓票 8小时 238元", @"鲫鱼票 24小时 58元" ];

    // 胶囊标签布局（自动换行，等间距）
    CGFloat contentLeft = 16.0;
    CGFloat contentRight = 16.0;
    CGFloat available = width - contentLeft - contentRight;
    CGFloat interItem = 12.0;
    CGFloat lineSpacing = 12.0;
    CGFloat tagHeight = 34.0;
    CGFloat currentX = contentLeft;
    CGFloat currentY = CGRectGetMaxY(title.frame) + 12.0;

    NSDictionary *attr = @{ NSFontAttributeName: [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold] };
    for (NSString *text in tags) {
        CGSize size = [text boundingRectWithSize:CGSizeMake(available, tagHeight)
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                      attributes:attr
                                         context:nil].size;
        CGFloat tagWidth = MIN(ceil(size.width) + 24.0, available);
        if (currentX + tagWidth > contentLeft + available) {
            // 换行
            currentX = contentLeft;
            currentY += (tagHeight + lineSpacing);
        }
        TagLabel *label = [TagLabel new];
        label.font = attr[NSFontAttributeName];
        label.text = text;
        label.frame = CGRectMake(currentX, currentY, tagWidth, tagHeight);
        [card addSubview:label];
        currentX += (tagWidth + interItem);
    }

    CGFloat bottom = currentY + tagHeight + 16.0;
    card.frame = CGRectMake(0, 0, width, bottom);
    return card;
}

- (UIView *)buildRuleCardWithWidth:(CGFloat)width {
    UIView *card = [[UIView alloc] initWithFrame:CGRectZero];
    card.backgroundColor = [UIColor systemBackgroundColor];
    card.layer.cornerRadius = 12.0;
    card.layer.masksToBounds = YES;
    
    // 标题与左侧色条
    UIView *indicator = [[UIView alloc] initWithFrame:CGRectMake(12, 18, 4, 18)];
    indicator.backgroundColor = whBlueColor;
    indicator.layer.cornerRadius = 2.0;
    [card addSubview:indicator];

   
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(indicator.frame) + 8, 12, 200, 28)];
    title.text = @"回鱼规则";
    title.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
    [card addSubview:title];

    // 表格：三列动态行高 + 表头 + 交替行底色 + 高亮数字
    CGFloat tableY = CGRectGetMaxY(title.frame) + 8;
    UIView *table = [[UIView alloc] initWithFrame:CGRectZero];
    [card addSubview:table];

    NSArray *rows = @[
        @[ @"鱼种", @"类型", @"回鱼标准" ], // header
        @[ @"鲢鳙", @"0.0斤至10.0斤", @"回鱼金额按25元/条计算\n回鱼会员金额按25元/条计算"],
        @[ @"鲢鳙", @"10.0斤至20.0斤", @"回鱼金额按50元/条计算\n回鱼会员金额按50元/条计算"],
        @[ @"鲢鳙", @"20.0斤至25.0斤", @"回鱼金额按100元/条计算\n回鱼会员票按120鱼票/条计算"],
        @[ @"鲢鳙", @"25.0斤至30.0斤", @"回鱼金额按160元/条计算\n回鱼会员票按160鱼票/条计算"],
        @[ @"鲢鳙", @"30.0斤至40.0斤", @"回鱼金额按200元/条计算\n回鱼会员票按220鱼票/条计算"],
        @[ @"鲢鳙", @"40.0斤至50.0斤", @"回鱼金额按240元/条计算\n回鱼会员票按240鱼票/条计算"]
    ];

    CGFloat col1W = 72.0, col2W = 112.0, col3W = width - 32 - col1W - col2W;
    CGFloat y = 0.0;
    UIFont *fontBody = [UIFont systemFontOfSize:16];
    UIFont *fontHeader = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];

    for (NSInteger i = 0; i < rows.count; i++) {
        NSArray *row = rows[i];
        BOOL isHeader = (i == 0);

        // dynamic height for col3 text
        NSString *col3Text = row[2];
        CGSize col3Size = [col3Text boundingRectWithSize:CGSizeMake(col3W - 16, CGFLOAT_MAX)
                                                 options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                              attributes:@{ NSFontAttributeName: isHeader ? fontHeader : fontBody }
                                                 context:nil].size;
        CGFloat rowHeight = MAX(56.0, ceil(col3Size.height) + 20.0);

        // alternate background for body rows
//        if (!isHeader && (i % 2 == 0)) {
//            UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, y, width - 32, rowHeight)];
//            bg.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1.0];
//            [table addSubview:bg];
//        }

        UILabel *c1 = [[UILabel alloc] initWithFrame:CGRectMake(0, y, col1W, rowHeight)];
        c1.textAlignment = NSTextAlignmentCenter;
        c1.textColor= [UIColor colorWithHexString:@"#767676" alpha:1.0];
        c1.numberOfLines = 0;
        c1.text = row[0];
        c1.font = isHeader ? fontHeader : [UIFont systemFontOfSize:16 weight:UIFontWeightLight];

        UILabel *c2 = [[UILabel alloc] initWithFrame:CGRectMake(col1W, y, col2W, rowHeight)];
        c2.textAlignment = NSTextAlignmentCenter;
        c2.textColor= [UIColor colorWithHexString:@"#767676" alpha:1.0];
        c2.numberOfLines = 0;
        c2.text = row[1];
        c2.font = isHeader ? fontHeader : fontBody;

        UILabel *c3 = [[UILabel alloc] initWithFrame:CGRectMake(col1W + col2W+5, y + 10, col3W - 16, rowHeight - 20)];
        c3.numberOfLines = 0;
        c3.textColor= [UIColor colorWithHexString:@"#767676" alpha:1.0];
        c3.font = isHeader ? fontHeader : fontBody;
        if (isHeader) {
            c3.text = row[2];
        } else {
            // highlight numbers in orange
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:col3Text attributes:@{ NSFontAttributeName: fontBody, NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#767676" alpha:1.0] }];
            NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9]+(\\.[0-9]+)?" options:0 error:nil];
            NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:col3Text options:0 range:NSMakeRange(0, col3Text.length)];
            UIColor *orange = [UIColor systemOrangeColor];
            for (NSTextCheckingResult *m in matches) {
                [attr addAttribute:NSForegroundColorAttributeName value:orange range:m.range];
                [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16 weight:UIFontWeightLight] range:m.range];
            }
            c3.attributedText = attr;
        }

        [table addSubview:c1];
        [table addSubview:c2];
        [table addSubview:c3];

        // vertical separators
        UIView *v1 = [[UIView alloc] initWithFrame:CGRectMake(col1W, y, 0.5, rowHeight)];
        UIView *v2 = [[UIView alloc] initWithFrame:CGRectMake(col1W + col2W, y, 0.5, rowHeight)];
        v1.backgroundColor = [UIColor separatorColor];
        v2.backgroundColor = [UIColor separatorColor];
        [table addSubview:v1];
        [table addSubview:v2];

        // bottom line
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, y + rowHeight, width - 32, 0.5)];
        line.backgroundColor = [UIColor separatorColor];
        [table addSubview:line];

        y += (rowHeight + 0.5);
    }

    table.frame = CGRectMake(16, tableY, width - 32, y);
    card.frame = CGRectMake(0, 0, width, CGRectGetMaxY(table.frame) + 12);
    return card;
}

@end


